﻿// **********************************************
// SharePoint WebPart: UsersADBrowser
// Author: Khristoforov Yuri
// WWW   : http://usersadbrowser.codeplex.com, http://activex.net.ru
// **********************************************

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Caching;
using UsersADBrowser.Helpers;

namespace UsersADBrowser.Controls
{
    public class UserInfoControl : System.Web.UI.UserControl
    {
        protected global::System.Web.UI.WebControls.DetailsView dvUserInfo;
        protected global::System.Web.UI.WebControls.Label lblErrorMsg;

        private const string _resourceGlobalName = "UsersADBrowser";

        private string _ldapProperties = "", _imageFormatUrl = "";
        private bool _isShowPhoto = false;
        private bool _isShowPresence = false;
        private int _imageDetailsWidth = 0;
        private int _cachingTime = 20;
        private string strAccountName, strAddress = "", strAddressType = "";
        private string[] _arrProps;
        private string[] _arrPropsInLower;

        public string LDAPProperties
        {
            get { return _ldapProperties; }
            set { _ldapProperties = value; }
        }

        public bool IsShowPresence
        {
            get { return _isShowPresence; }
            set { _isShowPresence = value; }
        }

        public bool IsShowPhoto
        {
            get { return _isShowPhoto; }
            set { _isShowPhoto = value; }
        }

        public string ImageFormatUrl
        {
            get { return _imageFormatUrl; }
            set { _imageFormatUrl = value; }
        }

        public int ImageWidth
        {
            get { return _imageDetailsWidth; }
            set { _imageDetailsWidth = value; }
        }

        public int CachingTime
        {
            get
            {
                return _cachingTime;
            }
            set
            {
                _cachingTime = value;
            }
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            lblErrorMsg.Visible = false;
            dvUserInfo.DataBound += new EventHandler(dvUserInfo_DataBound);
            InitUserDetaisView();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            strAccountName = Context.Request.QueryString["accountname"] != null ? Context.Request.QueryString["accountname"].Trim() : "";
            try
            {
                DataTable dtUserInfo = null;

                string strCacheKey = UsersADBrowserHelper.GetMD5("UsersADBrowser.UserInfo." + strAccountName + "." + LDAPProperties + "." + _isShowPhoto.ToString() + "." + _isShowPresence.ToString() + "." + _imageFormatUrl + "." + _cachingTime.ToString());
                object objCache = HttpContext.Current.Cache[strCacheKey];

                if (objCache == null)
                {
                    dtUserInfo = UsersADBrowserHelper.GetUserFromAD(strAccountName, _arrProps, _isShowPhoto, _isShowPresence);
                    HttpContext.Current.Cache.Insert(strCacheKey, dtUserInfo, null, DateTime.Now.AddMinutes(_cachingTime),
                                    Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
                }
                else
                {
                    dtUserInfo = (DataTable)objCache;
                }

                if (dtUserInfo.Rows.Count > 0 && _isShowPresence)
                {
                    string strAddresses = dtUserInfo.Rows[0]["UserPresence"].ToString();
                    string[] arrAddresses = strAddresses.Split(';');
                    string strSip = arrAddresses[0].Trim();
                    string strEmail = arrAddresses[1].Trim();
                    if (strSip != "")
                    {
                        strAddress = strSip;
                        strAddressType = "sip";
                    }
                    else if (strEmail != "")
                    {
                        strAddress = strEmail;
                        strAddressType = "smtp";
                    }
                }

                dvUserInfo.DataSource = dtUserInfo;
                dvUserInfo.DataBind();
            }
            catch (Exception ex)
            {
                lblErrorMsg.Visible = true;
                lblErrorMsg.Text = "GetUserFromAD error: " + ex.Message + "<br/>";
            }
        }

        private void InitUserDetaisView()
        {
            try
            {
                _arrProps = LDAPProperties.Replace(" ", "").Split(',');
                _arrPropsInLower = UsersADBrowserHelper.Values2Lower(_arrProps);

                if (IsShowPhoto)
                {
                    BoundField fldUserPhoto = new BoundField();
                    fldUserPhoto.DataField = "UserPhoto";
                    fldUserPhoto.HeaderText = HttpContext.GetGlobalResourceObject(_resourceGlobalName, "UserPhoto").ToString();
                    dvUserInfo.Fields.Add(fldUserPhoto);
                }

                for (int i = 0; i < _arrProps.Length; i++)
                {
                    BoundField fldUserInfo = new BoundField();
                    fldUserInfo.DataField = _arrProps[i].Trim();
                    fldUserInfo.HtmlEncode = false;
                    try
                    {
                        fldUserInfo.HeaderText = HttpContext.GetGlobalResourceObject(_resourceGlobalName, _arrProps[i].Trim()).ToString();
                    }
                    catch { }
                    dvUserInfo.Fields.Add(fldUserInfo);
                }
            }
            catch (Exception ex)
            {
                lblErrorMsg.Visible = true;
                lblErrorMsg.Text = "InitUserDetaisView error: " + ex.Message + "<br/>";
            }
        }

        void dvUserInfo_DataBound(object sender, EventArgs e)
        {
            int j = _isShowPhoto ? 1 : 0;

            // photo field
            if (_isShowPhoto)
            {
                dvUserInfo.Rows[0].Cells[1].Text = FieldTypeHelper.FormatImageField(strAccountName, _imageFormatUrl, _imageDetailsWidth);
            }

            // email address
            int idxField = Array.IndexOf(_arrPropsInLower, "mail");
            if (idxField != -1)
            {
                dvUserInfo.Rows[idxField + j].Cells[1].Text = FieldTypeHelper.FormatEmailField(dvUserInfo.Rows[idxField + j].Cells[1].Text);
            }

            // manager
            idxField = Array.IndexOf(_arrPropsInLower, "manager");
            if (idxField != -1)
            {
                dvUserInfo.Rows[idxField + j].Cells[1].Text = FieldTypeHelper.FormatManagerField(dvUserInfo.Rows[idxField + j].Cells[1].Text);
            }

            // modify first or second row
            if (_isShowPresence && strAddress != "")
            {
                dvUserInfo.Rows[j].Cells[1].Text = FieldTypeHelper.presenceHtmlCode.Replace("{SIPADDRESS}", strAddress).Replace("{GUID}", System.Guid.NewGuid().ToString()).Replace("{TYPE}", strAddressType) +
                                                    dvUserInfo.Rows[j].Cells[1].Text + "</span>";
            }

        }

    }
}